package com.dingpeikeji.quickdeer.modules.base.web;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.count.entity.CountInfo;
import com.dingpeikeji.quickdeer.core.modules.count.service.TCountService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Area;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Role;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.interceptor.FrontBaseInterceptor;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.google.common.collect.Lists;

/**
 * 用户注册
 * @author lh
 *
 */
@Controller
@RequestMapping("${frontPath}")
public class FSysController extends BaseController{
	
	public static final String FRONT_USER_IN_SESSION = "front_user";
	public static final String SAVE_USER_FOR_TREE_MONTHS = "saveUserFor3Months";

	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private FrontUserService userService;
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private TCountService tCountService;
	
	/**
	 * 登录
	 * @param model
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String doLogin(HttpServletRequest request,RedirectAttributes redirectAttributes, 
			HttpServletResponse response,Model model) throws Exception{
		String password = (String) request.getParameter("password");
		String username = (String) request.getParameter("username");
		String saveUserFor3Months = (String) request.getParameter("saveUserFor3Months");
		User user = (User)request.getSession().getAttribute(FRONT_USER_IN_SESSION);
		// 返回页面，先从地址参数中获取返回路径，如果没有则从session中获取
		String backPage = (String)request.getParameter("backUrl");
		if(StringUtils.isEmpty(backPage)) {
			backPage = (String)request.getSession().getAttribute(FrontBaseInterceptor.FRONT_BACK_URL_IN_SESSION);
		}
		if(StringUtils.isEmpty(backPage)) { // 如果没有任何路径，则直接进入首页
			backPage = frontPath + "/index";
		}
		String message = "";
		if(user != null) {
			return "redirect:"+backPage;
		} else { // 验证用户
				user = new User();
				user.setLoginName(username);
				List<User> userList = userService.findList(user);
				if(userList != null && !userList.isEmpty()) { // 存在用户
					user = userList.get(0);
					user.setOffice(officeService.get(user.getOffice()));
					if(user.getLoginFlag().equals("1") && "1".equals(user.getOffice().getUseable())){
						// 比对密码
						if(SystemService.validatePassword(password, user.getPassword())) {
							user = userList.get(0);
							Office office = officeService.get(user.getOffice()); // 用户所属部门
							user.setOffice(office);
							//int treeMonths = 30*24*60*60;
							if(StringUtils.isNotEmpty(saveUserFor3Months) && saveUserFor3Months.equals("yes")) {
								//勾选了30天自动登录
								Cookie cookie = new Cookie("autoLogin", user.getLoginName()+"#"+user.getPassword());
								cookie.setPath(request.getContextPath());
								cookie.setMaxAge(30* 24 * 60 * 60);
								response.addCookie(cookie);
							} 
							HttpSession session = request.getSession();
							session.setAttribute(FRONT_USER_IN_SESSION, user);
							if (backPage.contains("login")&&!backPage.contains("backUrl")) {
								backPage = frontPath + "/index";
								return "redirect:"+backPage;
							}else if(backPage.contains("backUrl")){
								String[] arr = backPage.split("backUrl=");
								return "redirect:"+arr[1];
							}
						}
						message = "用户名或密码不正确";
					} else {
						message = "该账号已禁用";
					}
				}else{
					message = "用户名不存在";
				}
		}
		request.getSession().setAttribute("mes", message);
		return "redirect:"+backPage;
	}
	/**
	 * 退出系统
	 * @param model
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request,RedirectAttributes redirectAttributes,HttpServletResponse response){
		User user = (User)request.getSession().getAttribute(FRONT_USER_IN_SESSION);
		if(user != null) {
			//request.getSession().removeAttribute(FRONT_USER_IN_SESSION);
			request.getSession().invalidate();
			// 清空自动登录的Cookie:
			Cookie cookie = new Cookie("autoLogin","");
			cookie.setPath(request.getContextPath());
			cookie.setMaxAge(0);
			response.addCookie(cookie);
			//redirectAttributes.addFlashAttribute("message", "已经注销");
		}
		return "redirect:"+frontPath+"/index";
	}

	@RequestMapping("doregister")
	public String doregister(User user, String validateCode,
			String officeName, RedirectAttributes redirectAttributes, 
			HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String failPage = "redirect:"+frontPath+"/index?register=yes";
		//String successPage = "redirect:"+frontPath+"/index?login=yes";原来的代码
		String successPage = "redirect:"+frontPath+"/index";
		List<String> messages = Lists.newArrayList(); // 消息
		String userType = user.getUserType();
		//单位注册
		if (validateCode==null) {
			validateCode = request.getParameter("validate2");
		}
		if (StringUtils.isEmpty(user.getMobile())) {
			user.setMobile(request.getParameter("mobile2"));
		}
		if (StringUtils.isEmpty(user.getNewPassword())) {
			user.setNewPassword((request.getParameter("confirmNewPassword2")));
		}
		String mobileFromRedisCode = jedisClient.get("registercode: "+user.getMobile());
		//List<String> validateCodeMsg = ValidateCodeTool.validateFromPhone(request, validateCode, FSmsController.validateCodeTypes[0]);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			messages.add("短信验证码超时");
		}
		if (StringUtil.isEmpty(validateCode)) {
			messages.add("短信验证码为空");
		}
		if (!mobileFromRedisCode.equals(validateCode)&&StringUtils.isNotBlank(mobileFromRedisCode)&&StringUtils.isNotBlank(validateCode)) {
			messages.add("短信验证码错误");
		}
		if(!messages.isEmpty()) { // 验证码校验不通过
			request.getSession().setAttribute("mes", messages.get(0));
			return "redirect:/register.jsp";
		} else {
			// 默认个人用户
			Office company = new Office();
			company.setId(Global.getConfig("front.companyid"));//0
			Office office = new Office();
			office.setId(Global.getConfig("front.officeid"));// "-"
			user.setCompany(company);
			user.setOffice(office);
			user.setLoginName(user.getMobile());
			if(ValidateTool.isEmptyOrNull(user.getName())) {
				user.setName(user.getMobile());
			}
			if (!beanValidator(redirectAttributes, user)){
				request.getRequestDispatcher("/register.jsp").forward(request, response);
				return null;
			}
			if("1".equals(userType) && ValidateTool.isEmptyOrNull(officeName)) {
				messages.add("请填写企业名称");
			}
			String parameter = request.getParameter("confirmNewPassword2");
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
			if (systemService.getUserByLoginName(user.getLoginName()) != null){
				messages.add("手机号已注册");
			}
		}
		if(messages.isEmpty()) {
			// 角色数据有效性验证，过滤不在授权内的角色
			List<Role> roleList = Lists.newArrayList();
			Role r = new Role();
			r.setId(Global.getConfig("front.roleid"));//2
			
			// 如果是企业注册
			if("1".equals(userType)) {
				r.setId(Global.getConfig("front.e.roleid"));
				
				// 新建普通单位
				Office office = new Office();
				String cid = UUID.randomUUID().toString().replace("-", "");
				office.setId(cid);
				Office parent = new Office();
				parent.setId(Global.getConfig("front.e.companyid"));
				office.setParent(parent);
				office.setParentIds("0,1,"+parent.getId()+",");
				office.setName(officeName);
				Area area = new Area();
				area.setId("20"); // 区域默认跟平台保持一致
				office.setArea(area);
				office.setType("2");
				office.setUseable("1"); // 可登陆
				office.setDelFlag("0"); // 未删除
				office.setFlatType("5");
				Date date = new Date();
				office.setCreateDate(date);
				office.setUpdateDate(date);
				User admin = new User(); // 操作用户默认都是管理员
				admin.setId("1");
				office.setCreateBy(admin);
				office.setUpdateBy(admin);
				officeService.savef(office); // 保存客运公司
				
				user.setCompany(office);
				user.setOffice(office);
			}
			roleList.add(r);
			user.setRoleList(roleList);
			systemService.savePubUser(user);
			//统计
			CountInfo countInfo=tCountService.findList(null).get(0);
			int t=countInfo.getHtmlNum()+1;
			countInfo.setHtmlNum(t);
			countInfo.setTotalCount(countInfo.getAndriodNum()+countInfo.getIosNum()+countInfo.getHtmlNum());
			tCountService.update(countInfo);
			return "redirect:/login.jsp";
		} else {
			request.getSession().setAttribute("mes", messages.get(0));
			return "redirect:/register.jsp";
		}
	}
	
	@RequestMapping(value = "user/forgetPwd")
	public String modifyPwd(String mobile, String password1, String password2,
			String validateCode, HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		List<String> messages = Lists.newArrayList(); // 消息
		String mobileFromRedisCode = jedisClient.get("registercode: "+mobile);
		//List<String> validateCodeMsg = ValidateCodeTool.validateFromPhone(request, validateCode, FSmsController.validateCodeTypes[0]);
		if (StringUtil.isEmpty(mobileFromRedisCode)) {
			messages.add("短信验证码超时");
		}
		if (!mobileFromRedisCode.equals(validateCode)) {
			messages.add("短信验证码错误");
		}
		if(messages.isEmpty()) {
				User user = new User();
				user.setLoginName(mobile);
				List<User> userList = systemService.findList(user);
				if(userList!=null && !userList.isEmpty()){
					user = userList.get(0);
					systemService.updatePasswordById(user.getId(), user.getLoginName(), password1);
					request.getSession().setAttribute("mes", "密码修改成功,请重新登录");
				} else {
					request.getSession().setAttribute("mes", "手机号未注册");
				}
		}else {
			request.getSession().setAttribute("mes", messages.get(0));
		}
		return "redirect:/password.jsp";
	}
	
	@RequestMapping(value = "modifyUserInfo")
	public String modifyUserInfo(HttpServletRequest request, Model model) {
		User user = (User)request.getSession().getAttribute(FRONT_USER_IN_SESSION);
		model.addAttribute("user", user);		
		return "/modules/base/personal";
		//return "modules/base/modifyUserInfo";
	}
	
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, String repeatPassword, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(repeatPassword)){
			if(!newPassword.equals(repeatPassword)){
				redirectAttributes.addFlashAttribute("message1", "两次密码输入不一致");
			}else if(!newPassword.matches(regex)){
				redirectAttributes.addFlashAttribute("message1", "修改密码失败，密码格式为6-16位数字和字母的组合");
			} else  {
				User user = (User)request.getSession().getAttribute(FRONT_USER_IN_SESSION);
				if (SystemService.validatePassword(oldPassword, user.getPassword())){
					systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
					redirectAttributes.addFlashAttribute("message1", "修改密码成功");
				}else{
					redirectAttributes.addFlashAttribute("message1", "修改密码失败，旧密码错误");
				}
			}
		} else {
			redirectAttributes.addFlashAttribute("message1", "请填写完整");
		}
		redirectAttributes.addFlashAttribute("fromPage","pwd");
		return "redirect:/f/modifyUserInfo?id=info";
	}
	
	/**
	 * 修改用户信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "modifyInfo",method=RequestMethod.POST)
	public String modifyInfo(User user, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		String regEx = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(user.getEmail());
		boolean rs = matcher.matches();
		if (!rs) {
			redirectAttributes.addFlashAttribute("message","邮箱格式不正确");
			return "redirect:/f/modifyUserInfo?id=info";
		}
		if(StringUtils.isBlank(user.getName()) ||
			StringUtils.isBlank(user.getEmail())||!rs){
			redirectAttributes.addFlashAttribute("message","请填写完整");
			return "redirect:/f/modifyUserInfo?id=info";
		} else {
			User opt = systemService.getUser(user.getId());
			if(opt != null){
				opt.setName(user.getName());
				opt.setEmail(user.getEmail());
				systemService.saveUser(opt);
				request.getSession().setAttribute(FRONT_USER_IN_SESSION, opt);
				redirectAttributes.addFlashAttribute("message","个人信息修改成功");
			}
		}
		return "redirect:/f/modifyUserInfo?id=info";
	}
}
